<template>
  <div class="contain">
    <div
      class="bar"
      v-for="item in letters"
      :key="item"
      :ref="item"
      @touchstart="handleTouchStart"
      @touchmove="handleTouchMove"
      @touchend="handleTouchEnd"
      @click="handleLetterClick"
    >
      <div class="item">{{item}}</div>
    </div>
  </div>
</template>

<script>
export default {
  name: "sidebar",
  props: ["cities"],
  data() {
    return {
      touchStatus: false,
      startY: 0,
      timer: null,
    };
  },
  computed: {
    letters() {
      const letters = [];
      for (let i in this.cities) {
        letters.push(i);
      }
      return letters;
    },
  },
  updated() {
    this.startY = this.$refs["A"][0].offsetTop;
  },
  methods: {
    handleLetterClick(e) {
      this.$emit("change", e.target.innerText);
      // console.log(e.target.innerText);
      // console.log(e);
    },
    handleTouchStart() {
      this.touchStatus = true;
    },
    handleTouchMove(e) {
      if (this.touchStatus === true) {
        if (this.timer) {
          clearTimeout(this.timer);
        }
        this.timer = setTimeout(() => {
          const touchY = e.touches[0].clientY;
          const index = Math.floor((touchY - this.startY) / 25.1) + 1;
          if (index >= 0 && index < this.letters.length) {
            this.$emit("change", this.letters[index]);
          }
        }, 16);
      }
    },
    handleTouchEnd() {
      this.touchStatus = false;
    },
  },
};
</script>

<style lang="stylus" scoped>
@import '~style/varibles.styl'

.contain
  position absolute
  top 0
  right 0
  bottom 0
  display flex
  flex-direction column
  justify-content center
  width 0.44rem
  height 100%
  color $bgColor

  .bar
    margin-bottom 0.1rem
    fong-size 0.4rem
</style>